import happybase
from db_class.mongdbClass import MongdbClass
import time

class HBaseClass():
    def __init__(self, host, port):
        self.clent = happybase.Connection(host, port, autoconnect=False)
        self.table_name = "news"
        self.clent.open()
        if not ( self.table_name.encode('utf-8') in self.clent.tables()):
            self.clent.create_table(
                self.table_name,
                {
                    "info": dict()
                }
            )
        if not self.clent.is_table_enabled(self.table_name):
            self.clent.enable_table(self.table_name)
        
        self.table = self.clent.table(self.table_name)
        self.clent.close()

    def addDate(self, data):
        self.clent.open()
        for item in data:
            self.table.put(item.get("id"), {
                "info:title": item.get("title"),
                "info:type": item.get("type"),
                "info:url": item.get("url"),
                # "info:time": item.get("time"),
                "info:date": str(item.get("date")),
                "info:month": str(item.get("month")),
                "info:year": str(item.get("year")),
                "info:time": str(int(time.mktime(time.strptime(f"{item.get('year')}-{item.get('month')}-{item.get('date')} {item.get('time')}","%Y-%m-%d %H:%M"))))
            })
        self.clent.close()

if __name__ == "__main__":
    mongo = MongdbClass("182.92.148.234", "Cache", "cache")
    data = []
    for i in mongo.findAll():
        data.append(i)

    db = HBaseClass("master", 9090)
    db.addDate(data)
    
